package com.jshan.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jshan.base.entity.SysDept;
import com.jshan.base.entity.SysUser;
import com.jshan.base.entity.SysUserDept;
import com.jshan.service.SysDeptService;
import com.jshan.service.SysUserDeptService;
import com.jshan.service.SysUserService;
import com.jshan.base.vo.Result;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.jshan.common.annotation.OperationLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Tag(name = "部门管理接口")
@RestController
@RequestMapping("/dept")
public class SysDeptController {

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysUserDeptService userDeptService;

    @Operation(summary = "部门列表")
    @GetMapping("/list")
    @SaCheckPermission("system:dept:list")
    public Result<List<SysDept>> list() {
        return Result.ok(deptService.listWithTree());
    }

    @Operation(summary = "部门分页列表")
    @GetMapping("/page")
    @SaCheckPermission("system:dept:list")
    public Result<IPage<SysDept>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String depName) {
        return Result.ok(deptService.getDeptPage(new Page<>(pageNum, pageSize), depName));
    }

    @OperationLog("根据ID获取部门信息")
    @GetMapping("/{id}")
    @SaCheckPermission("system:dept:query")
    public Result<SysDept> getById(@PathVariable Long id) {
        return Result.ok(deptService.getById(id));
    }

    @OperationLog("新增部门")
    @PostMapping
    @SaCheckPermission("system:dept:add")
    public Result<Void> add(@RequestBody SysDept dept) {
        deptService.save(dept);
        return Result.ok();
    }

    @OperationLog("修改部门")
    @PutMapping
    @SaCheckPermission("system:dept:edit")
    public Result<Void> update(@RequestBody SysDept dept) {
        deptService.updateById(dept);
        return Result.ok();
    }

    @OperationLog("删除部门")
    @DeleteMapping("/{id}")
    @SaCheckPermission("system:dept:remove")
    public Result<Void> delete(@PathVariable Long id) {
        deptService.removeById(id);
        return Result.ok();
    }

    @OperationLog("获取部门用户列表")
    @GetMapping("/users/{deptId}")
    @SaCheckPermission("system:dept:assign")
    public Result<List<SysUser>> getDeptUsers(@PathVariable Long deptId) {
        // 获取所有用户
        List<SysUser> allUsers = userService.list();

        // 获取已分配到当前部门的用户ID
        Set<Long> assignedUserIds = userDeptService.lambdaQuery()
                .eq(SysUserDept::getDeptId, deptId)
                .list()
                .stream()
                .map(SysUserDept::getUserId)
                .collect(Collectors.toSet());

        // 标记用户是否已分配
        allUsers.forEach(user -> {
            // 假定SysUser实体有一个setAssigned方法或者可以通过其他方式设置一个transient字段
            // 如果SysUser没有此方法，则需要修改SysUser实体或使用一个VO
            user.setAssigned(assignedUserIds.contains(user.getId()));
        });

        return Result.ok(allUsers);
    }

    @OperationLog("分配用户到部门")
    @PostMapping("/assignUsers")
    @SaCheckPermission("system:dept:assign")
    @Transactional
    public Result<Void> assignUsers(@RequestParam Long deptId, @RequestBody List<Long> userIds) {
        // 先移除该部门下所有用户的关联
        userDeptService.lambdaUpdate().eq(SysUserDept::getDeptId, deptId).remove();

        // 重新添加新的关联
        if (userIds != null && !userIds.isEmpty()) {
            List<SysUserDept> userDepts = new ArrayList<>();
            for (Long userId : userIds) {
                SysUserDept sysUserDept = new SysUserDept();
                sysUserDept.setDeptId(deptId);
                sysUserDept.setUserId(userId);
                userDepts.add(sysUserDept);
            }
            userDeptService.saveBatch(userDepts);
        }
        return Result.ok();
    }

    @OperationLog("从部门移除用户")
    @DeleteMapping("/removeUser")
    @SaCheckPermission("system:dept:assign")
    public Result<Void> removeUser(@RequestParam Long deptId, @RequestParam Long userId) {
        userDeptService.lambdaUpdate()
                .eq(SysUserDept::getDeptId, deptId)
                .eq(SysUserDept::getUserId, userId)
                .remove();
        return Result.ok();
    }
}
